package com.gitee.starblues.grape.rest;

import com.gitee.starblues.grape.core.domain.user.*;
import com.gitee.starblues.grape.core.exception.ChailvException;
import com.gitee.starblues.grape.core.service.UserRepository;
import com.gitee.starblues.grape.rest.common.BaseResource;
import com.gitee.starblues.grape.rest.common.Result;
import com.gitee.starblues.grape.rest.common.enums.ApiEnum;
import com.gitee.starblues.grape.utils.AuthUtils;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.util.List;

import static com.gitee.starblues.grape.rest.common.Result.*;

/**
 * @author l.zhu3
 * @date 2025/1/25 21:11
 */
@RestController
@RequestMapping(value = BaseResource.API + "chailv")
@AllArgsConstructor
@Api(tags = {"差旅相关接口"})
@Slf4j
public class ChailvController {

    @Resource
    private UserRepository userRepository;

    @GetMapping("/rebate-orders")
    @ApiOperation("分页获取返利订单")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "pageNum", value = "页码", defaultValue = "1"),
        @ApiImplicitParam(name = "pageSize", value = "每页数量", defaultValue = "10"),
        @ApiImplicitParam(name = "status", value = "订单状态(0:待返利,1:已返利,2:无返利)", required = false)
    })
    public Result<PageInfo<RebateOrder>> getRebateOrders(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) Integer status) {
        String username = AuthUtils.getCurrentUsername();
        return success(ApiEnum.GET_SUCCESS, userRepository.loadRebateOrders(username, pageNum, pageSize, status));
    }

    @PostMapping("/create-rebate-order")
    @ApiOperation("创建返利订单")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> createRebateOrder(@RequestBody RebateOrder order) {
        String username = AuthUtils.getCurrentUsername();
        // 设置用户名到订单对象
        order.setUserName(username);
        userRepository.addRebateOrder(order);
        return response(ApiEnum.ADD_SUCCESS);
    }

    @GetMapping("/draw-logs")
    @ApiOperation("获取提现记录")
    public Result<List<RebateDrawLog>> getDrawLogs() {
        String username = AuthUtils.getCurrentUsername();
        return success(ApiEnum.GET_SUCCESS, userRepository.loadRebateDrawLogs(username));
    }

    @PostMapping("/apply-withdraw")
    @ApiOperation("申请提现")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> applyWithdraw(@RequestBody RebateDrawLog drawLog) {
        try {
            String username = AuthUtils.getCurrentUsername();
            // 设置用户名到提现记录对象
            drawLog.setUserName(username);
            userRepository.addRebateDrawLog(drawLog);
            return response(ApiEnum.ADD_SUCCESS);
        } catch (ChailvException e) {
            return response(ApiEnum.ADD_SUCCESS);
        }
    }

    @GetMapping("/account-logs")
    @ApiOperation("获取账户收支明细")
    public Result<List<RebateAccountLog>> getAccountLogs() {
        String username = AuthUtils.getCurrentUsername();
        return success(ApiEnum.GET_SUCCESS, userRepository.loadRebateAccountLogs(username));
    }

    @GetMapping("/account")
    @ApiOperation("获取返利账户信息")
    public Result<RebateAccount> getRebateAccount() {
        String username = AuthUtils.getCurrentUsername();
        return success(ApiEnum.GET_SUCCESS, userRepository.loadRebateAccount(username));
    }

    @GetMapping("/user-accounts")
    @ApiOperation("获取用户账户列表")
    public Result<List<UserAccount>> getUserAccounts() {
        String username = AuthUtils.getCurrentUsername();
        return success(ApiEnum.GET_SUCCESS, userRepository.loadUserAccounts(username));
    }

    @PostMapping("/user-accounts")
    @ApiOperation("添加或更新用户账户")
    @Transactional(rollbackFor = Exception.class)
    public Result<String> addUserAccount(@RequestBody UserAccount userAccount) {
        try {
            String username = AuthUtils.getCurrentUsername();
            // 设置用户名到账户对象
            userAccount.setUserName(username);
            
            // 检查账户是否已存在
            List<UserAccount> existingAccounts = userRepository.loadUserAccounts(username);
            UserAccount existingAccount = existingAccounts.stream()
                    .filter(account -> account.getAccountType().equals(userAccount.getAccountType()))
                    .findFirst()
                    .orElse(null);
            
            if (existingAccount != null) {
                // 账户已存在，更新账户信息
                userAccount.setId(existingAccount.getId());
                userRepository.updateUserAccount(userAccount);
                return response(ApiEnum.UPDATE_SUCCESS);
            } else {
                // 账户不存在，新增账户
                userRepository.addUserAccount(userAccount);
                return response(ApiEnum.ADD_SUCCESS);
            }
        } catch (Exception e) {
            log.error("添加或更新用户账户失败", e);
            return failure(ApiEnum.ADD_ERROR, "添加或更新用户账户失败", e);
        }
    }
}
